package com.data.modules.online.cgform.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.Result;
import com.data.common.constant.enums.CgformEnum;
import com.data.common.system.query.QueryGenerator;
import com.data.common.system.util.JwtUtil;
import com.data.common.util.ConvertUtils;
import com.data.modules.online.cgform.entity.*;
import com.data.modules.online.cgform.service.IOnlCgformEnhanceService;
import com.data.modules.online.cgform.service.IOnlCgformFieldService;
import com.data.modules.online.cgform.service.IOnlCgformHeadService;
import com.data.modules.online.cgform.util.CgformUtil;
import com.data.modules.online.config.exception.DBException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.data.codegenerate.database.DbReadTableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.*;

/**
 *  onLine表单开发 列表控制器
 */
@Slf4j
@Api(tags = "onlCgformHeadController")
@RequestMapping("/online/cgform/head")
@RestController
@SuppressWarnings("ALL")
public class OnlCgformHeadController {

    private static List<String> f100b = null;

    private static String tempTbnames;
    @Autowired
    @Lazy
    private IOnlCgformEnhanceService onlCgformEnhanceService;
    @Autowired
    @Lazy
    private IOnlCgformFieldService onlCgformFieldService;
    @Autowired
    @Lazy
    private IOnlCgformHeadService onlCgformHeadService;
    @Autowired
    ResourceLoader resourceLoader;

    /** onLine表单开发 列表
     * @param onlCgformHead
     * @param num
     * @param num2
     * @param httpServletRequest
     * @return
     */
    @GetMapping({"/list"})
    public Result<IPage<OnlCgformHead>> list(OnlCgformHead onlCgformHead, @RequestParam(defaultValue = "1", name = "pageNo") Integer num, @RequestParam(defaultValue = "10", name = "pageSize") Integer num2, HttpServletRequest httpServletRequest) {
        Result<IPage<OnlCgformHead>> result = new Result<>();
        Wrapper initQueryWrapper = QueryGenerator.initQueryWrapper(onlCgformHead, httpServletRequest.getParameterMap());
        IPage page = this.onlCgformHeadService.page(new Page((long) num.intValue(), (long) num2.intValue()), initQueryWrapper);
        if (onlCgformHead.getCopyType() != null && onlCgformHead.getCopyType().intValue() == 0) {
            this.onlCgformHeadService.initCopyState(page.getRecords());
        }
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }

    /** onLine表单开发 新增
     * @param onlCgformHead
     * @return
     */
    @PostMapping({"/add"})
    public Result<OnlCgformHead> add(@RequestBody OnlCgformHead onlCgformHead) {
        Result<OnlCgformHead> result = new Result<>();
        try {
            this.onlCgformHeadService.save(onlCgformHead);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /** onLine表单开发 编辑
     * @param onlCgformHead
     * @return
     */
    @PutMapping({"/edit"})
    public Result<OnlCgformHead> edit(@RequestBody OnlCgformHead onlCgformHead) {
        Result<OnlCgformHead> result = new Result<>();
        if (((OnlCgformHead) this.onlCgformHeadService.getById(onlCgformHead.getId())) == null) {
            result.error500("未找到对应实体");
        } else if (this.onlCgformHeadService.updateById(onlCgformHead)) {
            result.success("修改成功!");
        }
        return result;
    }

    /** onLine表单开发 删除记录和表
     * @param str
     * @return
     */
    @DeleteMapping({"/delete"})
    public Result<?> delete(@RequestParam(name = "id", required = true) String str) {
        try {
            this.onlCgformHeadService.deleteRecordAndTable(str);
            return Result.ok("删除成功!");
        } catch (DBException e) {
            return Result.error("删除失败" + e.getMessage());
        } catch (SQLException e2) {
            return Result.error("删除失败" + e2.getMessage());
        }
    }

    /** onLine表单开发 删除记录
     * @param str
     * @return
     */
    @DeleteMapping({"/removeRecord"})
    public Result<?> removeRecord(@RequestParam(name = "id", required = true) String str) {
        try {
            this.onlCgformHeadService.deleteRecord(str);
            return Result.ok("移除成功!");
        } catch (DBException e) {
            return Result.error("移除失败" + e.getMessage());
        } catch (SQLException e2) {
            return Result.error("移除失败" + e2.getMessage());
        }
    }

    /** onLine表单开发 批量删除记录和表
     * @param str
     * @param str2
     * @return
     */
    @DeleteMapping({"/deleteBatch"})
    public Result<OnlCgformHead> deleteBatch(@RequestParam(name = "ids", required = true) String str, @RequestParam(name = "flag") String str2) {
        Result<OnlCgformHead> result = new Result<>();
        if (str == null || "".equals(str.trim())) {
            result.error500("参数不识别！");
        } else {
            this.onlCgformHeadService.deleteBatch(str, str2);
            result.success("删除成功!");
        }
        return result;
    }

    @GetMapping({"/queryById"})
    public Result<OnlCgformHead> queryById(@RequestParam(name = "id", required = true) String str) {
        Result<OnlCgformHead> result = new Result<>();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(str);
        if (onlCgformHead == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(onlCgformHead);
            result.setSuccess(true);
        }
        return result;
    }

    @GetMapping({"/queryByTableNames"})
    public Result<?> queryByTableNames(@RequestParam(name = "tableNames", required = true) String r4) {
        /*
            r3 = this;
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper r0 = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
            r0.<init>()
            String r1 = ","
            String[] r1 = r4.split(r1)
            r2 = move-result
            java.util.List r1 = java.util.Arrays.asList(r1)
            r0.in(r2, r1)
            org.jeecg.modules.online.cgform.service.IOnlCgformHeadService r1 = r3.onlCgformHeadService
            java.util.List r0 = r1.list(r0)
            if (r0 != 0) goto L_0x0025
            String r0 = "未找到对应实体"
            Result r0 = Result.error(r0)
        L_0x0024:
            return r0
        L_0x0025:
            Result r0 = Result.ok(r0)
            goto L_0x0024
        */
        throw new UnsupportedOperationException("Method not decompiled: com.data.modules.online.cgform.p008c.OnlCgformHeadController.mo365d(String):Result");
    }

    @PostMapping({"/enhanceJs/{code}"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo352a(@PathVariable("code") String str, @RequestBody OnlCgformEnhanceJs onlCgformEnhanceJs) {
        try {
            onlCgformEnhanceJs.setCgformHeadId(str);
            this.onlCgformHeadService.saveEnhance(onlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceJs/{code}"})
    public Result<?> mo350a(@PathVariable("code") String str, HttpServletRequest httpServletRequest) {
        try {
            OnlCgformEnhanceJs queryEnhance = this.onlCgformHeadService.queryEnhance(str, httpServletRequest.getParameter("type"));
            if (queryEnhance == null) {
                return Result.error("查询为空");
            }
            return Result.ok(queryEnhance);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("查询失败!");
        }
    }

    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    @PutMapping({"/enhanceJs/{code}"})
    public Result<?> mo359b(@PathVariable("code") String str, @RequestBody OnlCgformEnhanceJs onlCgformEnhanceJs) {
        try {
            onlCgformEnhanceJs.setCgformHeadId(str);
            this.onlCgformHeadService.editEnhance(onlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceButton/{formId}"})
    public Result<?> mo357b(@PathVariable("formId") String str, HttpServletRequest httpServletRequest) {
        try {
            List<OnlCgformButton> queryButtonList = this.onlCgformHeadService.queryButtonList(str);
            if (queryButtonList == null || queryButtonList.size() == 0) {
                return Result.error("查询为空");
            }
            return Result.ok(queryButtonList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("查询失败!");
        }
    }

    @GetMapping({"/enhanceSql/{formId}"})
    public Result<?> mo363c(@PathVariable("formId") String str, HttpServletRequest httpServletRequest) {
        return Result.OK(this.onlCgformEnhanceService.queryEnhanceSqlList(str));
    }

    @PostMapping({"/enhanceSql/{formId}"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo353a(@PathVariable("formId") String str, @RequestBody OnlCgformEnhanceSql onlCgformEnhanceSql) {
        try {
            onlCgformEnhanceSql.setCgformHeadId(str);
            if (!this.onlCgformEnhanceService.checkOnlyEnhance(onlCgformEnhanceSql)) {
                return Result.error("保存失败,该按钮已存在增强配置!");
            }
            this.onlCgformEnhanceService.saveEnhanceSql(onlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    @PutMapping({"/enhanceSql/{formId}"})
    public Result<?> mo360b(@PathVariable("formId") String str, @RequestBody OnlCgformEnhanceSql onlCgformEnhanceSql) {
        try {
            onlCgformEnhanceSql.setCgformHeadId(str);
            if (!this.onlCgformEnhanceService.checkOnlyEnhance(onlCgformEnhanceSql)) {
                return Result.error("保存失败,该按钮已存在增强配置!");
            }
            this.onlCgformEnhanceService.updateEnhanceSql(onlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @DeleteMapping({"/enhanceSql"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo367e(@RequestParam(name = "id", required = true) String str) {
        try {
            this.onlCgformEnhanceService.deleteEnhanceSql(str);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @DeleteMapping({"/deletebatchEnhanceSql"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo368f(@RequestParam(name = "ids", required = true) String str) {
        try {
            this.onlCgformEnhanceService.deleteBatchEnhanceSql(Arrays.asList(str.split(CgformUtil.f231E)));
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @GetMapping({"/enhanceJava/{formId}"})
    public Result<?> mo351a(@PathVariable("formId") String str, OnlCgformEnhanceJava onlCgformEnhanceJava) {
        return Result.OK(this.onlCgformEnhanceService.queryEnhanceJavaList(str));
    }

    @PostMapping({"/enhanceJava/{formId}"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo358b(@PathVariable("formId") String str, @RequestBody OnlCgformEnhanceJava onlCgformEnhanceJava) {
        try {
            if (!CgformUtil.m256a(onlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            }
            onlCgformEnhanceJava.setCgformHeadId(str);
            if (!this.onlCgformEnhanceService.checkOnlyEnhance(onlCgformEnhanceJava)) {
                return Result.error("保存失败：一个按钮、事件只能有一个增强！");
            }
            this.onlCgformEnhanceService.saveEnhanceJava(onlCgformEnhanceJava);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    @PutMapping({"/enhanceJava/{formId}"})
    public Result<?> mo364c(@PathVariable("formId") String str, @RequestBody OnlCgformEnhanceJava onlCgformEnhanceJava) {
        try {
            if (!CgformUtil.m256a(onlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            }
            onlCgformEnhanceJava.setCgformHeadId(str);
            if (!this.onlCgformEnhanceService.checkOnlyEnhance(onlCgformEnhanceJava)) {
                return Result.error("保存失败：一个按钮、事件只能有一个增强！");
            }
            this.onlCgformEnhanceService.updateEnhanceJava(onlCgformEnhanceJava);
            return Result.ok("保存成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("保存失败!");
        }
    }

    @DeleteMapping({"/enhanceJava"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo369g(@RequestParam(name = "id", required = true) String str) {
        try {
            this.onlCgformEnhanceService.deleteEnhanceJava(str);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @DeleteMapping({"/deleteBatchEnhanceJava"})
    @CacheEvict(allEntries = true, beforeInvocation = true, value = {"sys:cache:online:list", "sys:cache:online:form"})
    public Result<?> mo370h(@RequestParam(name = "ids", required = true) String str) {
        try {
            this.onlCgformEnhanceService.deleteBatchEnhanceJava(Arrays.asList(str.split(CgformUtil.f231E)));
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    /** 从数据库导入表单 列表
     * @param str
     * @param num
     * @param num2
     * @param httpServletRequest
     * @return
     */
    @GetMapping({"/queryTables"})
    public Result<?> mo348a(@RequestParam(name = "tableName", required = false) String str, @RequestParam(defaultValue = "1", name = "pageNo") Integer num, @RequestParam(defaultValue = "10", name = "pageSize") Integer num2, HttpServletRequest httpServletRequest) {
        if (!"admin".equals(JwtUtil.getUserNameByToken(httpServletRequest))) {
            return Result.error("noadminauth");
        }
//        new ArrayList();
        try {
            List readAllTableNames = DbReadTableUtil.readAllTableNames();
            CgformUtil.m270b(readAllTableNames);
            List<String> f = CgformUtil.m286f(readAllTableNames);
            List<String> queryOnlinetables = this.onlCgformHeadService.queryOnlinetables();
            m90b();
            f.removeAll(queryOnlinetables);
            ArrayList arrayList = new ArrayList();
            for (String str2 : f) {
                if (!m91l(str2)) {
                    HashMap hashMap = new HashMap();
                    hashMap.put("id", str2);
                    arrayList.add(hashMap);
                }
            }
            return Result.ok(arrayList);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
            return Result.error("同步失败，未获取数据库表信息");
        }
    }

    /** 从数据库导入表单
     * @param tbnames 表名
     * @param request
     * @return
     */
    @ApiOperation("从数据库导入表单")
    @PostMapping({"/transTables/{tbnames}"})
    public Result<?> transTables(@PathVariable("tbnames") String tbnames, HttpServletRequest request) {
        String name = JwtUtil.getUserNameByToken(request);
        if (!"admin".equals(name)) {
            return Result.error("noadminauth");
        } else if (ConvertUtils.isEmpty(tbnames)) {
            return Result.error("未识别的表名信息");
        } else if (tempTbnames != null && tempTbnames.equals(tbnames)) {
            return Result.error("不允许重复生成!");
        } else {
            tempTbnames = tbnames;
            String[] tableNames = tbnames.split(",");

            for(int i = 0; i < tableNames.length; ++i) {
                if (ConvertUtils.isNotEmpty(tableNames[i])) {
                    int var6 = this.onlCgformHeadService.count(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName,tableNames[i]));
                    if (var6 <= 0) {
                        this.onlCgformHeadService.saveDbTable2Online(tableNames[i]);
                    }
                }
            }

            tempTbnames = null;
            return Result.ok("同步完成!");
        }
    }

    @GetMapping({"/rootFile"})
    @RequiresRoles({"admin"})
    public Result<?> rootFile() {
        JSONArray jSONArray = new JSONArray();
        File[] listRoots = File.listRoots();
        for (File file : listRoots) {
            JSONObject jSONObject = new JSONObject();
            if (file.isDirectory()) {
                jSONObject.put("key", file.getAbsolutePath());
                jSONObject.put("title", file.getPath());
                jSONObject.put("opened", false);
                JSONObject jSONObject2 = new JSONObject();
                jSONObject2.put("icon", "custom");
                jSONObject.put("scopedSlots", jSONObject2);
                jSONObject.put("isLeaf", Boolean.valueOf(file.listFiles() == null || file.listFiles().length == 0));
            }
            jSONArray.add(jSONObject);
        }
        return Result.ok(jSONArray);
    }

    @GetMapping({"/fileTree"})
    @RequiresRoles({"admin"})
    public Result<?> mo371i(@RequestParam(name = "parentPath", required = true) String str) {
        JSONArray jSONArray = new JSONArray();
        File[] listFiles = new File(str).listFiles();
        for (File file : listFiles) {
            if (file.isDirectory() && ConvertUtils.isNotEmpty(file.getPath())) {
                JSONObject jSONObject = new JSONObject();
                System.out.println(file.getPath());
                jSONObject.put("key", file.getAbsolutePath());
                jSONObject.put("title", file.getPath().substring(file.getPath().lastIndexOf(File.separator) + 1));
                jSONObject.put("isLeaf", Boolean.valueOf(file.listFiles() == null || file.listFiles().length == 0));
                jSONObject.put("opened", false);
                JSONObject jSONObject2 = new JSONObject();
                jSONObject2.put("icon", "custom");
                jSONObject.put("scopedSlots", jSONObject2);
                jSONArray.add(jSONObject);
            }
        }
        return Result.ok(jSONArray);
    }


    /** 代码生成 详情
     * @param code
     * @return
     */
    @ApiOperation("代码生成 详情")
    @GetMapping({"/tableInfo"})
    public Result<?> tableInfo(@RequestParam(name = "code", required = true) String code) {
        OnlCgformHead head = (OnlCgformHead)this.onlCgformHeadService.getById(code);
        if (head == null) {
            return Result.error("未找到对应实体");
        } else {
            HashMap hashMap = new HashMap();
            hashMap.put("main", head);
            if (head.getTableType() == 2) {
                String var4 = head.getSubTableStr();
                if (ConvertUtils.isNotEmpty(var4)) {
                    ArrayList var5 = new ArrayList();
                    String[] var6 = var4.split(",");
                    String[] var7 = var6;
                    int var8 = var6.length;

                    for(int var9 = 0; var9 < var8; ++var9) {
                        String var10 = var7[var9];
                        LambdaQueryWrapper<OnlCgformHead> var11 = new LambdaQueryWrapper();
                        var11.eq(OnlCgformHead::getTableName, var10);
                        OnlCgformHead var12 = (OnlCgformHead)this.onlCgformHeadService.getOne(var11);
                        var5.add(var12);
                    }

                    Collections.sort(var5, new Comparator<OnlCgformHead>() {
                        public int compare(OnlCgformHead var1, OnlCgformHead var2) {
                            Integer var3 = var1.getTabOrderNum();
                            if (var3 == null) {
                                var3 = 0;
                            }

                            Integer var4 = var2.getTabOrderNum();
                            if (var4 == null) {
                                var4 = 0;
                            }

                            return var3.compareTo(var4);
                        }
                    });
                    hashMap.put("sub", var5);
                }
            }

            Integer var13 = head.getTableType();
            if ("Y".equals(head.getIsTree())) {
                var13 = 3;
            }

            List var14 = CgformEnum.getJspModelList(var13);
            hashMap.put("jspModeList", var14);
            hashMap.put("projectPath", DbReadTableUtil.getProjectPath());
            return Result.ok(hashMap);
        }
    }

    @PostMapping({"/copyOnline"})
    public Result<?> mo373k(@RequestParam(name = "code", required = true) String str) {
        try {
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(str);
            if (onlCgformHead == null) {
                return Result.error("未找到对应实体");
            }
            this.onlCgformHeadService.copyOnlineTableConfig(onlCgformHead);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("失败");
        }
    }

private boolean m91l(String r4) {
        Iterator var2 = f100b.iterator();

        String var3;
        do {
            if (!var2.hasNext()) {
                return false;
            }

            var3 = (String)var2.next();
        } while(!r4.startsWith(var3) && !r4.startsWith(var3.toUpperCase()));

        return true;
    }

    private void m90b() {
        if (f100b == null) {
            InputStream inputStream = null;
            try {
                InputStream inputStream2 = this.resourceLoader.getResource("classpath:conf" + File.separator + "boot_config.properties").getInputStream();
                Properties properties = new Properties();
                properties.load(inputStream2);
                String property = properties.getProperty("exclude_table");
                if (property != null) {
                    f100b = Arrays.asList(property.split(CgformUtil.f231E));
                }
                if (inputStream2 != null) {
                    try {
                        inputStream2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e2) {
                e2.printStackTrace();
                if (0 != 0) {
                    try {
                        inputStream.close();
                    } catch (IOException e3) {
                        e3.printStackTrace();
                    }
                }
            } catch (Throwable th) {
                if (0 != 0) {
                    try {
                        inputStream.close();
                    } catch (IOException e4) {
                        e4.printStackTrace();
                    }
                }
                throw th;
            }
        }
    }
}
